import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { OrderEntity } from '@/entity/order.entity';
import { ApiTags } from '@nestjs/swagger';
import { CreateOrderDto } from '@/modules/order/dto/create-order.dto';
import { UpdateOrderDto } from '@/modules/order/dto/update-order.dto';
import { RestaurantEntity } from '@/entity/restaurant.entity';

@ApiTags('订单模块')
@Injectable()
export class OrderService {
  constructor(
    @InjectRepository(OrderEntity)
    private readonly orderRepository: Repository<OrderEntity>,
    @InjectRepository(RestaurantEntity)
    private readonly restaurantRepository: Repository<RestaurantEntity>,
  ) {}

  async findAll(
    page = 1,
    limit = 10,
  ): Promise<{ list: OrderEntity[]; total: number }> {
    const queryBuilder = this.orderRepository
      .createQueryBuilder('o')
      .leftJoinAndSelect('o.restaurant', 'r')
      .leftJoinAndSelect('o.user', 'u')
      .orderBy('o.createTime', 'DESC')
      .skip((page - 1) * limit)
      .take(limit);

    const [data, total] = await queryBuilder.getManyAndCount();
    return {
      list: data,
      total,
    };
  }

  async findOne(id: number): Promise<OrderEntity> {
    const order = await this.orderRepository.findOne({ where: { id } });
    if (!order) {
      throw new NotFoundException('未找到该订单');
    }
    return order;
  }

  async findByUserId(userId: number): Promise<OrderEntity[]> {
    return this.orderRepository.find({ where: { userId } });
  }

  async findByUserAndStatus(
    userId: number,
    status: string,
  ): Promise<OrderEntity[]> {
    return this.orderRepository.find({ where: { userId, status } });
  }

  async create(createOrderDto: CreateOrderDto): Promise<OrderEntity> {
    const isRestaurant = await this.restaurantRepository.query(`
      SELECT * FROM restaurant_entity WHERE id = ${createOrderDto.restaurantId}`);
    if (!isRestaurant || isRestaurant.length === 0) {
      throw new NotFoundException('指定的餐厅不存在');
    }
    const order = this.orderRepository.create(createOrderDto);
    order.orderNo = Math.random().toString(36).substring(2, 18);
    return this.orderRepository.save(order);
  }

  async delete(id: number): Promise<void> {
    const result = await this.orderRepository.delete(id);
    if (result.affected === 0) {
      throw new NotFoundException('未找到该订单');
    }
  }

  async update(
    id: number,
    updateOrderDto: UpdateOrderDto,
  ): Promise<OrderEntity> {
    const order = await this.findOne(id);
    this.orderRepository.merge(order, updateOrderDto);
    return this.orderRepository.save(order);
  }
}
